import os
import cv2
import numpy as np
from PIL import Image
from utils.utils_fit import face_image_matching, onnx_runtime, update_dates
from utils.utils import image_transform


# camera相关类
class CameraVideoClass:
    video_index = 1

    # opencv人脸库文件

    def __init__(self):
        super(CameraVideoClass, self).__init__()
        self.video = None

    def CameraInit(self):
        self.video = cv2.VideoCapture(CameraVideoClass.video_index, cv2.CAP_DSHOW)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 4000)  # 设置图像宽度
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 3036)  # 设置图像高度
        self.video.set(cv2.CAP_PROP_FPS, 30)
        self.video.set(cv2.CAP_PROP_EXPOSURE, 50000)  # 调整曝光时间1.0-5000
        self.video.set(cv2.CAP_PROP_BRIGHTNESS, 64)

    def CaptureCamera(self):
        if self.video is not None:
            ret, frame = self.video.read()
            if ret:
                frame = cv2.resize(frame, (500, 450))
                frame = cv2.flip(frame, 1)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                return frame
        else:
            return None

    def SetCamera(self):
        pass

    def ExitCamera(self):
        self.video.release()


CADES_PATH = "haarcascade_frontalface_default.xml"


# OPENCV检测人脸
def OpenFaceClassifier(img):
    faces = []
    classifier = cv2.CascadeClassifier(cv2.data.haarcascades + CADES_PATH)
    facerects = classifier.detectMultiScale(img)
    if len(facerects) > 0:
        for rect in facerects:
            x, y, w, h = rect
            if w > 100:
                face = img[y:(y + h), x:(x + w)]
                face = cv2.resize(face, (100, 100))
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                faces.append(face)
    if len(faces) != 0:

        return img, faces
    else:
        return img, None


# 人脸识别
def FaceRecognition(img):
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    img = image_transform(img)
    img = onnx_runtime(img)
    features_distance, images_path = face_image_matching(img)
    if np.min(np.array(features_distance)) < 1.2:
        min_arg = np.argmin(np.array(features_distance))
        mathing = cv2.imread(images_path[min_arg])
        mathing = cv2.cvtColor(mathing, cv2.COLOR_BGR2RGB)
        return mathing
    else:
        return None


# 定义人脸录入
def InputFace(imglist, name):
    if imglist is not None:
        img_path = './source/images/' + name + '.jpg'
        img = cv2.cvtColor(imglist[0], cv2.COLOR_RGB2BGR)
        cv2.imwrite(img_path, img)
        return img_path
    else:
        return None


# 定义取消将要录入的人脸
def CancelFace(path):
    os.remove(path)


# 定义完成人脸信息录入
def CompleteFaceInfoInput(path):
    img = cv2.imread(path)
    pathlist = path.split('/')[-1]
    cv2.imwrite('../resources/face_datas/' + pathlist, img)
    update_dates()
    os.remove(path)


image_paths = "../resources/face_datas/"


# 打开文件夹
def OpenFile():
    images_path = []
    dirs = os.listdir(image_paths)
    for dir in dirs:
        images_path.append(image_paths + dir)
    return images_path


# 读取图片
def ReadImage(path):
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img


# 删除图片
def DeleteImage(path):
    os.remove(path)
    images_path = OpenFile()
    return images_path


# 显示照片
def ShowImage(path):
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img


# 修改图片信息
def ModificationImage(index, imagelist, moditext):
    img = cv2.imread(imagelist[index])
    cv2.imwrite('../resources/face_datas/' + moditext + '.jpg', img)
    os.remove(imagelist[index])
    images_path = OpenFile()
    return images_path
